// http://192.168.20.80:8077/swagger/v1/swagger.json
var fs = require('fs');
var request = require('request');
const {base64encode} = require('nodejs-base64')
/*
* url 网络文件地址
* filename 文件名
* callback 回调函数
*/
function downloadFile(uri,filename,callback){
  var stream = fs.createWriteStream(filename);
  request(uri).pipe(stream).on('close', callback); 
}
/**
 * @function 对base64后的字符串进行混淆
 * @param {String} str 要转换的字符串 
 */
function changeStr (str) {
  let arr = str.split('')
  let arr1 = arr.filter((item, index) => {
    return index % 2 === 0
  })
  let arr2 = arr.filter((item, index) => {
    return index % 2 === 1
  })
  let str1 = ''
  for (let i in arr1.length > arr2.length ? arr1 : arr2) {
    if (arr2[i] !== undefined) {
      str1 = str1 + arr2[i]
    }
    if (arr1[i] !== undefined) {
      str1 = str1 + arr1[i]
    }
  }
  return str1
}

var fileUrl  = 'http://47.97.111.86:8019/swagger/v1/swagger.json'; // 改IP就可以了
var filename = './src/apis/download.json';
downloadFile(fileUrl,filename,function(){
  console.log(filename+'下载完毕');

  var jsonData = require('./download.json')
  let txt = ''
  for (let i in jsonData.paths) {
    try {
      txt += `  ${jsonData.paths[i]['post'].operationId}: '${changeStr(base64encode(i))}', // ${jsonData.paths[i]['post'].summary}\n`
    } catch (e) {
      txt += `  ${jsonData.paths[i]['get'].operationId}: '${changeStr(base64encode(i))}', // ${jsonData.paths[i]['get'].summary}\n`
    }
  }
  fs.writeFile('./src/apis.js',`const { base64decode } = require('nodejs-base64')
const apis = {
${txt}
  }
  if (process.env.NODE_ENV === 'development') {
    Object.keys(apis).forEach((key) => {
      apis[key] = \`/apis\${base64decode(changeStr(apis[key]))}\`
    })
  } else {
    Object.keys(apis).forEach((key) => {
      apis[key] = \`\${base64decode(changeStr(apis[key]))}\`
    })
  }
  function changeStr (str) {
    let arr = str.split('')
    let arr1 = arr.filter((item, index) => {
      return index % 2 === 0
    })
    let arr2 = arr.filter((item, index) => {
      return index % 2 === 1
    })
    let str1 = ''
    for (let i in arr1.length > arr2.length ? arr1 : arr2) {
      if (arr2[i] !== undefined) {
        str1 = str1 + arr2[i]
      }
      if (arr1[i] !== undefined) {
        str1 = str1 + arr1[i]
      }
    }
    return str1
  }
  export default apis
  `,function(err){
    if(err) throw err;
    console.log('写入完成');
  });

});




